package t_02_nio.group_chat;

import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer(6666);
        groupChatServer.listen();
    }

    private final Selector selector;
    private final ServerSocketChannel listenChannel;

    @SneakyThrows
    public GroupChatServer(Integer port) { // 构造器，初始化工作
        listenChannel = ServerSocketChannel.open(); // ServerSocketChannel
        listenChannel.socket().bind(new InetSocketAddress(port)); // 绑定端口
        listenChannel.configureBlocking(false); // 设置非阻塞模式
        selector = Selector.open(); // 得到选择器
        listenChannel.register(selector, SelectionKey.OP_ACCEPT); // 将该 listenChannel 注册到 selector
    }

    // 监听
    @SneakyThrows
    public void listen() {
        System.out.println("监听线程: " + Thread.currentThread().getName());
        // 循环处理
        while (true) {
            int count = selector.select();
            if (count > 0) { // 有事件处理
                // 遍历得到 selectionKey 集合
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next(); // 取出 selectionKey
                    if (key.isAcceptable()) { // 监听到 accept
                        SocketChannel sc = listenChannel.accept();
                        sc.configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ); // 将该 sc 注册到 seletor
                        System.out.println(sc.getRemoteAddress() + " 上线 "); // 提示
                    }
                    if (key.isReadable()) { // 通道发送 read 事件，即通道是可读的状态
                        readData(key); // 处理读 (专门写方法..)
                    }
                    iterator.remove(); // 当前的 key 删除，防止重复处理
                }
            } else {
                System.out.println("等待....");
            }
        }
    }

    private void readData(SelectionKey key) { // 读取客户端消息
        SocketChannel channel = null; // 取到关联的 channle
        try {
            channel = (SocketChannel) key.channel(); // 得到 channel
            ByteBuffer buffer = ByteBuffer.allocate(1024); // 创建 buffer
            int count = channel.read(buffer);
            // 根据 count 的值做处理
            if (count > 0) {
                String msg = new String(buffer.array()); // 把缓存区的数据转成字符串
                System.out.println("form 客户端: " + msg); // 输出该消息
                sendInfoToOtherClients(msg, channel); // 向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                key.cancel(); // 取消注册
                channel.close(); // 关闭通道
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }

    // 转发消息给其它客户(通道)
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
        // 遍历所有注册到 selector 上的 SocketChannel，并排除 self
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel(); // 通过 key  取出对应的 SocketChannel
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                SocketChannel dest = (SocketChannel) targetChannel; // 转型
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); // 将 msg 存储到 buffer
                dest.write(buffer); // 将 buffer 的数据写入通道
            }
        }
    }
}


